from django.shortcuts import render_to_response, HttpResponseRedirect
from django.template import RequestContext
from django.conf import settings
from models import User
from django.db import connections
from django.contrib.auth import hashers

def verify_auth(request):
	logged=request.session.get('logged')
	if not logged:
		return render_to_response('login.html', request.session, context_instance=RequestContext(request))
	return HttpResponseRedirect("home")

def login(request):

	logged=request.session.get('logged')
	if logged:
		return HttpResponseRedirect("home")

	username =request.POST.get('username')
	password =request.POST.get('password')

	user=None
	try:
		user = User.objects.get(username=username)
	except:
		pass

	logged=False
	if user is not None:
		logged=user.authenticate(password)
	else:
		return HttpResponseRedirect("/")

	if logged:
		request.session.set_expiry(1200)
		request.session['logged']=True
		request.session['user']=user
		return HttpResponseRedirect("home")
	else:
		return HttpResponseRedirect("/")

def logout(request):
	logged=request.session.get('logged')
	if logged:
		for sesskey in request.session.keys():
			print sesskey
			del request.session[sesskey]
	return HttpResponseRedirect("/")


def home(request):
	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	databases=len(settings.DATABASES)

	tables=0
	views=0

	for database in settings.DATABASES:
		cursor = connections[database].cursor()
		cursor.execute("SELECT count(*) FROM sqlite_master WHERE type = 'table'")
		tables += cursor.fetchone()[0]
		cursor.execute("SELECT count(*) FROM sqlite_master WHERE type = 'view'")
		views += cursor.fetchone()[0]

	user=request.session.get('user')

	response_vars= {'databases':databases,
					'tables':tables,
					'views':views,
					'user':user
	}

	return render_to_response('index.html', response_vars, context_instance=RequestContext(request))

def add(request):

	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	user=request.session.get('user')
	databases=settings.DATABASES
	default_colums=list(xrange(0,4))
	return render_to_response("add.html", {'user':user,'databases':databases,'cols':default_colums}, context_instance=RequestContext(request))

def add_table(request):

	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	database=request.POST.get('database')
	query=request.POST.get('query')

	cursor = connections[database].cursor()
	cursor.execute(query)

	return HttpResponseRedirect("home")

def update(request):

	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	user=request.session.get('user')
	databases=settings.DATABASES
	database=request.POST.get('database') if request.POST.get('database') else 'default'
	tables=get_tables(database)

	response_vars= {'user':user,
					'databases':databases,
					'database':database,
					'tables':tables,
					'delete':False}

	return render_to_response("list.html", response_vars, context_instance=RequestContext(request))

def delete(request):

	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	user=request.session.get('user')
	databases=settings.DATABASES
	database=request.POST.get('database') if request.POST.get('database') else 'default'
	tables=get_tables(database)

	response_vars= {'user':user,
					'databases':databases,
					'database':database,
					'tables':tables,
					'delete':True}
	return render_to_response("list.html",response_vars, context_instance=RequestContext(request))

def remove_table(request):
	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	database=request.POST.get('database')
	table_name=request.POST.get('table-id')

	cursor=connections[database].cursor()
	cursor.execute("DROP TABLE "+table_name)
	return HttpResponseRedirect("delete")


def get_tables(database):

	table_list=[]
	cursor=connections[database].cursor()
	cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")

	tables=cursor.fetchall()

	for table in tables:
		tablename=str(table[0])
		columns=len(cursor.execute("PRAGMA table_info("+tablename+")").fetchall())
		records=cursor.execute("SELECT count(*) FROM "+tablename).fetchone()[0]
		item={'name':tablename,'cols':columns,'recs':records}
		table_list.append(item)

	return table_list

def load_data(request):

	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	col_list=[]
	user=request.session.get('user')
	database=request.POST.get('database')
	table_name=request.POST.get('table-id')

	cursor=connections[database].cursor()
	cursor.execute("PRAGMA table_info("+table_name+")")

	columns=cursor.fetchall()

	for column in columns:
		col_name=column[1]
		col_type=column[2].split('(')[0].strip()
		col_size=column[2].split('(')[1].split(')')[0] if column[2].find('(')>0 else ''
		is_null=column[3]
		item={'name':col_name,'type':col_type,'size':col_size,'no_null':is_null}
		print item
		col_list.append(item)

	response_vars= {'editing':True,
					'cols':col_list,
					'tablename':table_name,
					'user':user}

	return render_to_response("add.html",response_vars, context_instance=RequestContext(request))

def results(request):
	if not request.session.get('logged'):
		return HttpResponseRedirect("/")

	return render_to_response("results.html", request.session, context_instance=RequestContext(request))

def page_not_found(request):
	return render_to_response("404.html", request.session, context_instance=RequestContext(request))

def server_error(request):
	return render_to_response("500.html", request.session, context_instance=RequestContext(request))

def account(request):
	user=request.session.get('user')
	return render_to_response("account.html",{'user':user}, context_instance=RequestContext(request))

def acco_update(request):

	first_name=request.POST.get('first-name')
	last_name=request.POST.get('last-name')
	passwd=request.POST.get('password')

	user=request.session.get('user')
	user.first_name=first_name
	user.last_name=last_name

	if(user.authenticate(passwd) is False):
		user.password=hashers.make_password(passwd)

	user.save()
	request.session['user']=user

	return HttpResponseRedirect("/")

def config(request):
	return render_to_response("settings.html", request.session, context_instance=RequestContext(request))